import {defineStore} from "pinia";
import router from "@/router";
import store from "@/store/store";

const useTagStore = defineStore("tagStore", {
  state() {
    return {
      //访问历史
      visitData: JSON.parse(localStorage.getItem("visitData") || "[]"),
      //需要缓存的路由
      cacheData: [] as Array<any>
    };
  },
  actions: {
    addTag(route: any) {
      let name = "";
      if (route.matched && route.matched.length) {
        route.matched.forEach((item: any) => {
          if ((!item.children || !item.children.length) && !item.meta.noCache) {
            name = item.components.default.__name;
          }
        });
      }
      let isHaveHome = this.visitData.find((item) => {
        return item.meta.title == "首页";
      });
      if (!isHaveHome) {
        let homePage: any = router
          .getRoutes()
          .find((item) => item.meta.title == "首页");
        //添加首页
        this.visitData.push({
          path: homePage.redirect || homePage.path,
          name: homePage.components.default.__name,
          meta: {
            title: "首页"
          }
        });
      }
      let isHave = this.visitData.findIndex((item) => {
        return item.path == route.path;
      });
      if (isHave >= 0) {
        return false;
      }
      if (route.meta.title === "首页") {
        return false;
      }
      let newRoute = {
        path: route.path,
        name,
        meta: {
          title: route.meta.title
        }
      };
      this.visitData.push(JSON.parse(JSON.stringify(newRoute)));
      localStorage.setItem("visitData", JSON.stringify(this.visitData));
    },
    closeTag(route: any) {
      //清除某个历史记录
      let index = this.visitData.findIndex((item) => {
        return item.path == route.path;
      });
      this.visitData.splice(index, 1);
      let indexCache = this.cacheData.findIndex((item) => {
        return item == route.name;
      });
      this.cacheData.splice(indexCache, 1);
      if (!this.visitData.length) {
        localStorage.removeItem("visitData");
      } else {
        localStorage.setItem("visitData", JSON.stringify(this.visitData));
      }
    },
    addCache(route: any) {
      if (route.matched && route.matched.length) {
        route.matched.forEach((item: any) => {
          let name = item.components.default.__name;
          if (name) {
            if (
              (!item.children || !item.children.length) &&
              !item.meta.noCache &&
              !this.cacheData.includes(name)
            ) {
              this.cacheData.push(name);
            }
          }
        });
      }
    }
  }
});

export default useTagStore(store);
